<template>
    <div class="ssh-client">
        <!-- 顶部标题栏 -->
        <div class="content-header">
            <h1 class="content-title">SSH连接管理</h1>
            <div class="action-buttons">
                <button class="btn btn-secondary" @click="loadSavedServers">
                    <i class="fas fa-download"></i> 加载保存的服务器
                </button>
                <button class="btn btn-primary" @click="switchToFileManager">
                    <i class="fas fa-folder"></i> 文件管理
                </button>
            </div>
        </div>

        <!-- 连接面板 -->
        <div class="connection-panel">
            <div class="connection-form">
                <div class="form-group">
                    <label for="savedServers">快速连接</label>
                    <select
                        id="savedServers"
                        v-model="selectedServerId"
                        @change="loadServerConfig"
                    >
                        <option value="">选择已保存的服务器...</option>
                        <option
                            v-for="server in savedServers"
                            :key="server.id"
                            :value="server.id"
                        >
                            {{ server.name }} ({{ server.host }}:{{
                                server.port
                            }})
                        </option>
                    </select>
                </div>
                <div class="form-group">
                    <label for="host">服务器地址</label>
                    <input
                        type="text"
                        id="host"
                        v-model="host"
                        placeholder="192.168.1.100 或 example.com"
                        value="localhost"
                    />
                </div>
                <div class="form-group">
                    <label for="port">端口</label>
                    <input
                        type="number"
                        id="port"
                        v-model="port"
                        placeholder="22"
                        value="22"
                    />
                </div>
                <div class="form-group">
                    <label for="username">用户名</label>
                    <input
                        type="text"
                        id="username"
                        v-model="username"
                        placeholder="root"
                    />
                </div>
                <div class="form-group">
                    <label for="password">密码</label>
                    <input
                        type="password"
                        id="password"
                        v-model="password"
                        placeholder="密码"
                    />
                </div>
                <div class="form-group">
                    <label for="serverName">服务器名称（可选）</label>
                    <input
                        type="text"
                        id="serverName"
                        v-model="serverName"
                        placeholder="给服务器起个名字"
                    />
                </div>
            </div>

            <div class="checkbox-group">
                <input type="checkbox" id="saveServer" v-model="saveServer" />
                <label for="saveServer">保存服务器配置</label>
            </div>

            <div class="action-buttons" style="margin-top: 15px">
                <button
                    class="btn btn-primary"
                    @click="connect"
                    :disabled="connected"
                >
                    <i class="fas fa-plug"></i> 连接
                </button>
                <button
                    class="btn btn-success"
                    @click="testConnection"
                    id="testBtn"
                >
                    <i class="fas fa-check"></i> 测试连接
                </button>
                <button
                    class="btn btn-danger"
                    @click="disconnect"
                    :disabled="!connected"
                >
                    <i class="fas fa-unplug"></i> 断开连接
                </button>
            </div>
        </div>

        <!-- 终端容器 -->
        <div class="terminal-container" :class="{ hidden: !connected }">
            <div class="terminal-header">
                <div class="terminal-info">
                    <div class="connection-status">
                        <span class="tab-status connected"></span>
                        <span>{{ currentServerName }}</span>
                    </div>
                    <div id="terminalStats">行: 30, 列: 120</div>
                </div>
                <div class="terminal-actions">
                    <button class="terminal-btn" @click="fitTerminal">
                        <i class="fas fa-expand"></i> 适应窗口
                    </button>
                </div>
            </div>
            <div class="terminal-wrapper">
                <div id="terminal"></div>
            </div>
            <div class="status-bar">
                <div>状态: {{ connectionStatus }}</div>
                <div>Web SSH 企业版客户端</div>
            </div>
        </div>
        <!-- 终端容器 -->
        <div class="terminal-container hidden" id="terminalContainer">
            <!-- Tab栏 -->
            <div class="terminal-tabs" id="terminalTabs">
                <!-- tabs will be added dynamically -->
            </div>

            <!-- Terminal内容区 -->
            <div class="terminal-content" id="terminalContent">
                <!-- terminals will be added dynamically -->
            </div>

            <div class="status-bar">
                <span id="statusBar">就绪</span>
                <span id="terminalStats">行: 24, 列: 80</span>
            </div>
        </div>

        <!-- 提示框 -->
        <div
            v-if="alertMessage"
            :class="['alert', 'alert-' + alertType]"
            @click="clearAlert"
        >
            {{ alertMessage }}
        </div>
    </div>
</template>

<script>
import menu from "@/views/pages/system/components/menu";
import { moduleName } from "@/config";

export default {
    data: () => ({
        description: "ssh客户端",
        buttons: {
            search: { name: "查询" },
            add: { name: "添加" },
            restore: { name: "恢复出厂设置" },
            edit: { name: "编辑" },
            del: { name: "删除" },
            addChild: { name: "添加子级" },
            addBtn: { name: "添加按钮" },
        },
        // type 0:目录 1：菜单 2：按钮
        type: "1",
        icon: "Platform",
        name: "ssh客户端",
        parentMenu: menu,
        module: moduleName,
    }),
};
</script>

<script setup>
import { onMounted, ref, onUnmounted } from "vue";
import { useRouter } from "vue-router";

// 路由
const router = useRouter();

// 表单数据
const host = ref("localhost");
const port = ref(22);
const username = ref("");
const password = ref("");
const serverName = ref("");
const selectedServerId = ref("");
const saveServer = ref(false);

// 状态管理
const connected = ref(false);
const currentServerName = ref("");
const connectionStatus = ref("未连接");
const savedServers = ref([]);
const alertMessage = ref("");
const alertType = ref("");

// 终端相关
let terminal = null;
let fitAddon = null;
let websocket = null;

// 初始化终端
const initializeTerminal = () => {
    if (window.Terminal && window.FitAddon) {
        terminal = new window.Terminal({
            cursorBlink: true,
            fontSize: 14,
            fontFamily: 'Monaco, Menlo, "Ubuntu Mono", Consolas, monospace',
            theme: {
                background: "#1e1e1e",
                foreground: "#d4d4d4",
                cursor: "#ffffff",
                selection: "#ffffff40",
            },
            rows: 30,
            cols: 120,
        });

        fitAddon = new window.FitAddon.FitAddon();
        terminal.loadAddon(fitAddon);

        const terminalElement = document.getElementById("terminal");
        if (terminalElement) {
            terminal.open(terminalElement);
            fitAddon.fit();
        }

        // 监听窗口大小变化
        window.addEventListener("resize", handleResize);

        // 处理终端输入
        terminal.onData((data) => {
            if (
                connected.value &&
                websocket &&
                websocket.readyState === WebSocket.OPEN
            ) {
                websocket.send(
                    JSON.stringify({
                        type: "command",
                        command: data,
                    }),
                );
            }
        });

        // 处理终端大小变化
        terminal.onResize((size) => {
            document.getElementById("terminalStats").textContent =
                `行: ${size.rows}, 列: ${size.cols}`;

            if (
                connected.value &&
                websocket &&
                websocket.readyState === WebSocket.OPEN
            ) {
                websocket.send(
                    JSON.stringify({
                        type: "resize",
                        cols: size.cols,
                        rows: size.rows,
                    }),
                );
            }
        });
    }
};

// 窗口大小变化处理
const handleResize = () => {
    if (fitAddon) {
        setTimeout(() => fitAddon.fit(), 100);
    }
};

// 适应终端大小
const fitTerminal = () => {
    if (fitAddon) {
        fitAddon.fit();
    }
};

// 加载保存的服务器
const loadSavedServers = async () => {
    try {
        const { code, data } = await VE_API.ssh.sshServersFindList();

        console.log(data);
        if (code === 0) {
            savedServers.value = data;
            showAlert("服务器列表加载成功", "success");
        } else {
            // 业务错误已在axios拦截器中处理
            console.warn("获取服务器列表失败:", data?.message);
        }
    } catch (error) {
        console.error("加载服务器列表失败:", error);
        showAlert("加载服务器列表失败", "danger");
    }
};

// 加载服务器配置
const loadServerConfig = async () => {
    if (!selectedServerId.value) return;

    try {
        const { code, data } = await VE_API.ssh.sshServersFindById({
            id: selectedServerId.value,
        });

        if (code === 0) {
            const server = data;

            host.value = server.host;
            port.value = server.port;
            username.value = server.username;
            serverName.value = server.name;
            password.value = ""; // 安全考虑不加载密码
        }
    } catch (error) {
        console.error("加载服务器配置失败:", error);
        showAlert("加载服务器配置失败", "danger");
    }
};

// 连接SSH
const connect = async () => {
    if (connected.value) {
        showAlert("已有连接存在，请先断开", "danger");
        return;
    }

    if (!host.value || !port.value || !username.value) {
        showAlert("请填写必要的连接信息", "danger");
        return;
    }

    const serverInfo = {
        host: host.value,
        port: port.value,
        username: username.value,
        password: password.value,
        name:
            serverName.value || `${username.value}@${host.value}:${port.value}`,
    };

    currentServerName.value = serverInfo.name;

    try {
        const protocol = window.location.protocol === "https:" ? "wss:" : "ws:";
        const wsUrl = `${protocol}//${window.location.host}/ssh`;
        websocket = new WebSocket(wsUrl);

        websocket.onopen = () => {
            console.log("WebSocket连接建立");
            connectionStatus.value = "正在连接SSH...";

            // 发送SSH连接请求
            websocket.send(
                JSON.stringify({
                    type: "connect",
                    host: serverInfo.host,
                    port: parseInt(serverInfo.port),
                    username: serverInfo.username,
                    password: serverInfo.password,
                }),
            );
        };

        websocket.onmessage = (event) => {
            const message = JSON.parse(event.data);
            handleWebSocketMessage(message);
        };

        websocket.onerror = (error) => {
            console.error("WebSocket错误:", error);
            showAlert("WebSocket连接错误", "danger");
            if (terminal) {
                terminal.writeln("\r\n❌ WebSocket连接错误");
            }
        };

        websocket.onclose = () => {
            console.log("WebSocket连接关闭");
            handleDisconnection();
        };
    } catch (error) {
        console.error("连接失败:", error);
        showAlert("连接失败: " + error.message, "danger");
    }
};
// test连接SSH
const testConnection = async () => {
    if (!host.value || !port.value || !username.value) {
        showAlert("请填写必要的连接信息", "danger");
        return;
    }
    const serverInfo = {
        host: host.value,
        port: port.value,
        username: username.value,
        password: password.value,
        name:
            serverName.value || `${username.value}@${host.value}:${port.value}`,
    };

    currentServerName.value = serverInfo.name;

    try {
        const { code, message } = await VE_API.ssh.sshServerTest(serverInfo);

        if (code === 0) {
            showAlert("连接测试成功", "success");
        } else {
            showAlert("连接测试失败: " + message, "danger");
        }
    } catch (error) {
        console.error("连接测试失败:", error);
        showAlert("连接测试失败", "danger");
    }
};

// 处理WebSocket消息
const handleWebSocketMessage = (message) => {
    console.log("message:" + message);
    switch (message.type) {
        case "connected":
            connected.value = true;
            connectionStatus.value = "已连接";

            if (terminal) {
                terminal.clear();
                terminal.writeln("🎉 SSH连接建立成功!");
                terminal.writeln(`连接到: ${currentServerName.value}`);
                terminal.writeln("");
            }

            showAlert("SSH连接成功", "success");

            // 保存服务器配置
            if (saveServer.value) {
                saveServerConfig();
            }
            break;

        case "output":
            if (terminal) {
                terminal.write(message.data);
            }
            break;

        case "error":
            if (terminal) {
                terminal.writeln(`\r\n❌ 错误: ${message.message}`);
            }
            showAlert(`连接失败: ${message.message}`, "danger");
            connectionStatus.value = "连接失败";
            break;
    }
};

// 断开连接
const disconnect = () => {
    if (websocket) {
        websocket.send(
            JSON.stringify({
                type: "disconnect",
            }),
        );
        websocket.close();
    }
    handleDisconnection();
};

// 处理断开连接
const handleDisconnection = () => {
    connected.value = false;
    currentServerName.value = "";
    connectionStatus.value = "已断开连接";

    if (terminal) {
        terminal.writeln("\r\n🔌 连接已关闭");
    }

    showAlert("SSH连接已断开", "danger");
};

// 保存服务器配置
const saveServerConfig = async () => {
    const serverData = {
        name: serverName.value || `${username.value}@${host.value}`,
        host: host.value,
        port: parseInt(port.value),
        username: username.value,
        password: password.value,
    };

    try {
        const response = VE_API.ssh.sshServerStory(serverData);

        //     await fetch("/api/servers", {
        //     method: "POST",
        //     headers: {
        //         "Content-Type": "application/json",
        //     },
        //     body: JSON.stringify(serverData),
        // });

        if (response.ok) {
            showAlert("服务器配置保存成功", "success");
            await loadSavedServers(); // 重新加载服务器列表
        } else {
            const error = await response.json();
            showAlert(`保存失败: ${error.message}`, "danger");
        }
    } catch (error) {
        console.error("保存服务器配置失败:", error);
        showAlert("保存服务器配置失败", "danger");
    }
};

// 显示提示信息
const showAlert = (message, type = "info") => {
    alertMessage.value = message;
    alertType.value = type;

    // 3秒后自动清除提示
    setTimeout(() => {
        alertMessage.value = "";
    }, 3000);
};

// 清除提示
const clearAlert = () => {
    alertMessage.value = "";
};

// 切换到文件管理页面
const switchToFileManager = () => {
    router.push("/files");
};

// 组件挂载时初始化
onMounted(() => {
    initializeTerminal();
    loadSavedServers();
});

// 组件卸载时清理
onUnmounted(() => {
    window.removeEventListener("resize", handleResize);
    if (websocket) {
        websocket.close();
    }
});
</script>

<style scoped>
/* 继承原CSS样式，保持一致的UI体验 */
.ssh-client {
    padding: 20px;
    height: 100vh;
    box-sizing: border-box;
    background: #f5f7fa;
}

.content-header {
    background: #fff;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    margin-bottom: 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.content-title {
    font-size: 24px;
    font-weight: 600;
    color: #333;
    margin: 0;
}

.action-buttons {
    display: flex;
    gap: 10px;
}

.connection-panel {
    background: #fff;
    padding: 25px;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    margin-bottom: 20px;
}

.connection-form {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    gap: 20px;
    margin-bottom: 20px;
}

.form-group {
    display: flex;
    flex-direction: column;
}

.form-group label {
    margin-bottom: 8px;
    font-weight: 500;
    color: #333;
}

.form-group input,
.form-group select {
    padding: 12px;
    border: 1px solid #ddd;
    border-radius: 6px;
    font-size: 14px;
    transition: border-color 0.2s;
}

.form-group input:focus,
.form-group select:focus {
    outline: none;
    border-color: #1da1f2;
    box-shadow: 0 0 0 3px rgba(29, 161, 242, 0.1);
}

.checkbox-group {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-top: 15px;
}

.checkbox-group input[type="checkbox"] {
    width: auto;
}

.btn {
    padding: 12px 24px;
    border: none;
    border-radius: 6px;
    cursor: pointer;
    font-size: 14px;
    font-weight: 500;
    transition: all 0.2s;
    display: inline-flex;
    align-items: center;
    gap: 8px;
    text-decoration: none;
}

.btn-primary {
    background: #1da1f2;
    color: white;
}

.btn-primary:hover {
    background: #1991db;
    transform: translateY(-1px);
}

.btn-danger {
    background: #dc3545;
    color: white;
}

.btn-danger:hover {
    background: #c82333;
}

.btn-secondary {
    background: #6c757d;
    color: white;
}

.btn-secondary:hover {
    background: #545b62;
}

.btn:disabled {
    opacity: 0.6;
    cursor: not-allowed;
    transform: none;
}

.terminal-container {
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    overflow: hidden;
    margin-bottom: 20px;
    display: flex;
    flex-direction: column;
    height: 600px;
}

.terminal-header {
    background: #2d3748;
    color: white;
    padding: 10px 15px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    min-height: 40px;
}

.terminal-info {
    display: flex;
    align-items: center;
    gap: 15px;
}

.connection-status {
    font-size: 13px;
    font-weight: 500;
    display: flex;
    align-items: center;
    gap: 6px;
}

.tab-status {
    width: 8px;
    height: 8px;
    border-radius: 50%;
}

.tab-status.connected {
    background: #28a745;
}

.terminal-actions {
    display: flex;
    gap: 8px;
}

.terminal-btn {
    background: rgba(255, 255, 255, 0.1);
    border: none;
    color: white;
    padding: 6px 10px;
    border-radius: 4px;
    cursor: pointer;
    font-size: 11px;
    transition: background-color 0.2s;
}

.terminal-btn:hover {
    background: rgba(255, 255, 255, 0.2);
}

.terminal-wrapper {
    flex: 1;
    padding: 10px;
    background: #1e1e1e;
}

#terminal {
    width: 100%;
    height: 100%;
}

.status-bar {
    background: #f8f9fa;
    padding: 10px 20px;
    border-top: 1px solid #dee2e6;
    font-size: 12px;
    color: #6c757d;
    display: flex;
    justify-content: space-between;
}

.alert {
    padding: 12px 16px;
    margin-bottom: 20px;
    border: 1px solid transparent;
    border-radius: 6px;
    font-size: 14px;
    cursor: pointer;
}

.alert-success {
    color: #155724;
    background-color: #d4edda;
    border-color: #c3e6cb;
}

.alert-danger {
    color: #721c24;
    background-color: #f8d7da;
    border-color: #f5c6cb;
}

.alert-info {
    color: #0c5460;
    background-color: #d1ecf1;
    border-color: #bee5eb;
}

.hidden {
    display: none !important;
}

@media (max-width: 768px) {
    .connection-form {
        grid-template-columns: 1fr;
    }
}
</style>
